<?php

/**
 * 视图渲染类
 *
 * 先尽量简化，实现模板功能即可
 *
 * @author heshun
 */

require_library('framework.template');

class View extends Template {

    /**
     * 当前使用的模板的名字，是post不是post.phtml
     */
    private $themeName = '';

    // 当前页面所在的应用，项目
    private $app = '';
    private $project = '';

    private $pagePath = NULL;

    public function __construct($themeName = '', $app = APP, $project = PROJECT)
    {
        $this->themeName = $themeName;
        $this->app       = $app;
        $this->project   = $project;
        $this->appId     = get_app_id($app, $project);
        $this->pagePath  = self::getPagePath($this->app, $this->project);

        parent::__construct();
    }

    public function render($page, $contentType = Template::DEFAULT_CONTENT_TYPE)
    {
        if (empty($page) || empty($contentType))
        {
            throw new cls_exception('invalid_args');
        }

        $this->init($page, $contentType);

        $this->display();
    }

    public function init($page, $contentType = Template::DEFAULT_CONTENT_TYPE)
    {
        $this->contentType  = $contentType;
        $this->fullPathTemplateFile = $this->pagePath . '/' . $this->themeName . self::PAGE_TEMPLATE_SUFFIX;
        // 设置标题
        $this->assign('PAGE_TITLE', $this->_generalTitle());
    }
    
    public function setTitle($titleKey, $option = 'APPEND')
    {
        switch ($option)
        {
            case 'APPEND':
            case 'OVERWRITE':
                break;

            default:
                throw new cls_exception('invalid_args');
        }

        $this->titles[] = array('titleKey' => $titleKey, 'option' => $option);
        return $this;
    }

    private function _generalTitle()
    {
        $delimiter = '_';
        // array (title' =>'标题1','option' =>'append');
        // array (title' =>'标题2','option' =>'append');
        $userDefineTitle = array();
        if (count($this->titles) > 0)
        {
            $tmp = $this->titles;
            $temp = array_pop($tmp);

            $userDefineTitle = array('titleKey' => $temp['titleKey'], 'option' => $temp['option'] == 'APPEND' ? 'APPEND' : 'OVERWRITE');
            for ($i = count($tmp) - 1; $i >= 0; $i--)
            {
                if ($tmp[$i]['option'] === 'APPEND')
                {
                    $userDefineTitle['titleKey'] .= $delimiter . $tmp[$i]['titleKey'];
                }
                else    // 覆盖 OVERWRITE
                {
                    $userDefineTitle['titleKey'] = $tmp[$i]['titleKey'];
                }
            }
        }

        $result = array($userDefineTitle['titleKey']);
        $locale = $GLOBALS['PROJECT_CONFIG']['locale'];
        if ($userDefineTitle['option'] == 'APPEND' && !empty($GLOBALS['TITLE_CONFIGS'][$locale][CONTROLLER][ACTION]))
        {
            $result[] = $GLOBALS['TITLE_CONFIGS'][$locale][$url];
        }

        if (defined('PROJECT_DESCRIPTION'))
        {
            $result[] = PROJECT_DESCRIPTION;
        }

        return htmlspecialchars(implode($delimiter, $result), ENT_QUOTES, 'UTF-8');
    }

    // 简单的包含文件进来是不行的，因为模板里面就是执行PHP语句 $this->import()出来的
    // import需要new一个view类来解析
    public function import($fullPageName)
    {
        $parts  = explode('.', $fullPageName);
        switch (count($parts))
        {
            case 1:
                $subPageName = $fullPageName;
                $sub = new View($this->themeName, $this->editMode, $this->app, $this->project);
                $configPath = PageUtil::getPagePath($this->themeName, $this->app, $this->project);
                break;

            case 2:
                list($app, $subPageName) = $parts;
                $sub = new Page($this->themeName, $this->editMode, $app, $this->project);
                $configPath = PageUtil::getPagePath($this->themeName, $app, $this->project);
                break;

            default:
                throw new cls_exception('invalid_sub_page_name@import');
        }

        self::$entireContainerSettings[$subPageName] = PageUtil::buildContainerDefaultSettings($configPath, $subPageName);
        if ($this->editMode === true && PageUtil::isFooter($subPageName))
        {
            $containerSettings = array();
            foreach (self::$entireContainerSettings as $settings)
            {
                foreach ($settings as $val)
                {
                    $containerSettings[] = array($val['name'], $val['page'], $val['allowedWidgets'], $val['editable']);
                }
            }

            $alteredWidgets = array();
            foreach (array_keys(self::$entireContainerSettings) as $page)
            {
                $arrayKey = $page . '_' . $this->styleFactor;
                if (!empty($GLOBALS['_SESSION']->PageSettings['altered'][$arrayKey]))
                {
                    $alteredWidgets = array_merge($alteredWidgets, $GLOBALS['_SESSION']->PageSettings['altered'][$arrayKey]);
                }
            }

            $vars = array(
                'containerSettings' => addslashes(json_encode($containerSettings)),
                'editMode' => $this->editMode,
                'editorScripts' => $this->editorScripts(),
            );

            if (empty($alteredWidgets))
            {
                $vars['alteredWidgets'] = addslashes(json_encode(array()));
                $vars['pageAltered'] = false;
            }
            else
            {
                $vars['alteredWidgets'] = addslashes(json_encode(array_values($alteredWidgets)));
                $vars['pageAltered'] = true;
            }
            $sub->assign($vars);
        }

        foreach ($this->titles as $v)
        {
            if (empty($v['titleKey']) || empty($v['option']))
            {
                continue;
            }
            $sub->setTitle($v['titleKey'], $v['option']);
        }

        $sub->assign($this->getTemplateVars());
        $sub->setContext($this->shareContext);
        $sub->setMeta($this->meta);
        $sub->setAllEchoPolicyOff();
        $sub->show($subPageName);
    }


    static public function getPagePath($app, $project)
    {
        $theme = empty($GLOBALS['SERVICE_CONFIG']['theme']) ? $app : $GLOBALS['SERVICE_CONFIG']['theme'];
        $path = get_app_path(get_app_id($app, $project), true, $project) . '/theme/' . $theme;
//dump($path);
        if (file_exists($path))
        {
            return $path;
        }

        throw new APF_Exception('can_not_locate_page_path');
    }


}
?>
